package com.example.sls.service.impl.account;

import com.example.sls.mapper.account.AccountMapper;
import com.example.sls.pojo.account.Account;
import com.example.sls.service.account.ResetPasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class ResetPasswordServiceImpl implements ResetPasswordService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public Map<String, String> resetPassword(String username, String phone, String password, String confirmedPassword, Integer roleId) {
        Map<String, String> res = new HashMap<>();

        Account acc = accountMapper.getAccountByUserName(username);

        if(acc == null){
            res.put("error_message", "用户名不存在");
            return  res;
        }

        Integer id = acc.getId();

        if(!acc.getPhone().equals(phone)){
            res.put("error_message", "手机号不符");
            return  res;
        }
        if(! acc.getRoleId().equals(roleId)){
            res.put("error_message", "账号角色不符");
            return  res;
        }
        if(!password.equals(confirmedPassword)){
            res.put("error_message", "两次密码不一致");
            return  res;
        }

        String encodedPassword = passwordEncoder.encode(confirmedPassword);

        if(accountMapper.resetPassword(encodedPassword, id) > 0){
            res.put("error_message", "success");
            return res;
        }
        else{
            res.put("error_message", "密码重置出错");
            return  res;
        }
    }
}
